package com.example.pieces.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import com.example.pieces.MainActivity;
import com.example.pieces.za.Constants;
import com.example.pieces.R;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by Administrator on 2016/9/19 0019.
 */
public class ChessboardView extends View implements View.OnTouchListener{
    public  static int a=0;
    public  static int ab=1;
    private Context context;
    public static String status;
    // 记录黑白棋子位置的列表
    public static List<Point> mwhiteArray = new ArrayList<>();
    public  static List<Point> mblackArray = new ArrayList<>();
    private Paint paint;
    private static final String TAG = "ChessboardView";
    private int width,heigh;//棋盘宽高
    private float cellWandH;//单元格长宽
    private float bilv= (float) 0.5;//比率
    private Bitmap black,white;//棋子对象
    private MainActivity main=null;
    public ChessboardView(Context context) {
        super(context);
        this.context=context;
        init();
    }

    public ChessboardView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context=context;
        init();
    }

    public ChessboardView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context=context;
        init();
    }

    /**
     * 初始化操作
     */
    private void init() {
        status=main.status;
        //初始化画笔
        paint=new Paint();
        //设置画笔颜色，此时会比默认显示浅一点。
        paint.setColor(0x88000000);
        //抗锯齿
        paint.setAntiAlias(true);
        //防抖动
        paint.setDither(true);
        //设置填充样式，如果不设置，默认全部填充（FILL），另外样式：1.Paint.Style.STROKE：描边 2.Paint.Style.FILL_AND_STROKE：描边并填充
        paint.setStyle(Paint.Style.STROKE);
        //通过资源得到bitmap对象
        white = BitmapFactory.decodeResource(getResources(), R.mipmap.white);
        black = BitmapFactory.decodeResource(getResources(), R.mipmap.black);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        width=MeasureSpec.getSize(widthMeasureSpec);
        heigh=MeasureSpec.getSize(heightMeasureSpec);
       setMeasuredDimension(width*6/7,heigh*6/7);
    }
    //@Override
//    public boolean onTouchEvent(MotionEvent event) {
//        int action=event.getAction();
//        if (status.equals("1")|status.equals("2")) {
//            Toast.makeText(context, "棋局结束,请返回大厅！", Toast.LENGTH_SHORT).show();
//        }else if (status.equals("0")){
//            if (action==MotionEvent.ACTION_UP) {
//                int x= (int) event.getX();//得到点击处距离子view左边距离
//                int y= (int) event.getY();//得到点击处距离子view右边距离
//                int validX = (int) (x / cellWandH);
//                int validY = (int) (y / cellWandH);
//                Point point = getValidPoint(x, y);
//                String player=main.player;
//
//                if (mwhiteArray.contains(point) || mblackArray.contains(point)) {
//                    Toast.makeText(getContext(), "请勿重复落子！", Toast.LENGTH_SHORT).show();
//                    return false;
//                }
//
//                if (player.equals("player2")) {
//                    if (ab% 2 != 0) {
//                        mblackArray.add(point);
//                        main.anxia(validX,validY);
//                    }else{
//                        Toast.makeText(context, "被挑战者，请等待对方下子！", Toast.LENGTH_SHORT).show();
//                    }
//                }else if (player.equals("player1")){
//                    if (ab % 2 == 0) {
//                        mwhiteArray.add(point);
//                        main.anxia(validX,validY);
//                    }else{
//                        Toast.makeText(context, "挑战者，请等待对方下子！", Toast.LENGTH_SHORT).show();
//                    }
//                }
//                invalidate();//刷新UI
//            }
//        }
//        return true;
//    }
    /**
     * 刷新界面调用postInvalidate()能在非UI线程刷新
     */
    public void setPointToArray(Point point) {
        a++;
        ab=++ab;
        status=main.status;
        String player=main.player;
        if (player.equals("player2")&a%2==0) {//被挑战者
            mwhiteArray.add(point);
//            for (int i = 0, n = mwhiteArray.size(); i < n; i++) {//mwhiteArray:记录白色棋子位置的列表。
//                Log.e(TAG,"白色棋子数组："+mwhiteArray.get(i));
//            }
        }else if (player.equals("player1")&a%2!=0){//挑战者
            mblackArray.add(point);
//            for (int i = 0, n = mblackArray.size(); i < n; i++) {
//                Log.e(TAG,"黑色棋子数组："+mblackArray.get(i));
//            }
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                postInvalidate();
                Log.e(TAG,"postInvalidate执行了");
            }
        }).start();
    }

    /**
     * 得到具体横纵坐标。
     * @param x
     * @param y
     * @return
     */
    public Point getValidPoint(int x, int y) {
        int validX = (int) (x / cellWandH);
        int validY = (int) (y / cellWandH);
        return new Point(validX, validY);
    }
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        //棋盘每格的长宽，虽然棋盘长宽不一样，但是每个单元格要保持为正方形。
        cellWandH = w * 1.0f / Constants.MAX_LINE_X;//
        //棋子的长宽。
        int pieceWidth = (int) (cellWandH * bilv);
        //第一个参数是待修改的Bitmap,第二第三个参数分别为修改后的宽、高，最后一个Boolean参数暂时不知什么作用。
        //createScaledBitmap：根据原来的位图创建一个新的位图。此时设置新位图长宽都是单元格长宽的二分之一。
        white = Bitmap.createScaledBitmap(white, pieceWidth, pieceWidth, false);
        black = Bitmap.createScaledBitmap(black, pieceWidth, pieceWidth, false);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawBoard(canvas);
        drawPieces(canvas);
        Log.e(TAG,"onDraw执行了");
    }


    /**
     * 绘制黑白棋子
     * @param canvas
     */
    private void drawPieces(Canvas canvas) {
        for (int i = 0, n = mwhiteArray.size(); i < n; i++) {//mwhiteArray:记录白色棋子位置的列表。
            Point whitePoint = mwhiteArray.get(i);//得到数组中对应索引的位置对象。
            float left = (whitePoint.x +(1 - bilv) / 2) * cellWandH;
            float top = (whitePoint.y + (1 - bilv) / 2) * cellWandH;
            canvas.drawBitmap(white, left, top, null);
        }

        for (int i = 0, n = mblackArray.size(); i < n; i++) {
            Point blackPoint = mblackArray.get(i);
            float left = (blackPoint.x + (1 - bilv) / 2) * cellWandH;
            float top = (blackPoint.y + (1 - bilv) / 2) * cellWandH;
            canvas.drawBitmap(black, left, top, null);
        }
    }

    /**
     *  绘制棋盘的网格
     * @param canvas
     */
    private void drawBoard(Canvas canvas) {
        for (int i = 0; i < Constants.MAX_LINE_X; i++) {
            int startX = (int) (cellWandH/2);
            int endX = (int) (cellWandH*21+startX);
            int y = (int) ((0.5 + i) * cellWandH);
            canvas.drawLine(y, startX, y, endX, paint);//上下的线
        }
        for (int i = 0; i <= Constants.MAX_LINE_Y; i++) {
            int startX = (int) (cellWandH /2);//如果不这样设置距边界距离，画出来的是网格线，而不是棋盘
            float endX = (cellWandH*14 + startX);
            float y = (float) ((0.5 + i) * cellWandH);
            canvas.drawLine(startX, y, endX, y, paint);//左右的线
        }
    }

    public void clearArr() {
        ab++;
        a++;
        main.status="0";
        mwhiteArray.clear();
        mblackArray.clear();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int action=event.getAction();
        if (status.equals("1")|status.equals("2")) {
            Toast.makeText(context, "棋局结束,请返回大厅！", Toast.LENGTH_SHORT).show();
        }else if (status.equals("0")){
            if (action==MotionEvent.ACTION_UP) {
                int x= (int) event.getX();//得到点击处距离子view左边距离
                int y= (int) event.getY();//得到点击处距离子view右边距离
                int validX = (int) (x / cellWandH);
                int validY = (int) (y / cellWandH);
                Point point = getValidPoint(x, y);
                String player=main.player;

                if (mwhiteArray.contains(point) || mblackArray.contains(point)) {
                    Toast.makeText(getContext(), "请勿重复落子！", Toast.LENGTH_SHORT).show();
                    return false;
                }

                if (player.equals("player2")) {
                    if (ab% 2 != 0) {
                        mblackArray.add(point);
                        main.anxia(validX,validY);
                    }else{
                        Toast.makeText(context, "被挑战者，请等待对方下子！", Toast.LENGTH_SHORT).show();
                    }
                }else if (player.equals("player1")){
                    if (ab % 2 == 0) {
                        mwhiteArray.add(point);
                        main.anxia(validX,validY);
                    }else{
                        Toast.makeText(context, "挑战者，请等待对方下子！", Toast.LENGTH_SHORT).show();
                    }
                }
                invalidate();//刷新UI
            }
        }
        return true;
    }
}
